package com.uphone.magicleafteacher.util;

import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.SeekBar;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.radish.baselibrary.utils.ToastUtil;

public class AudioPlayProgressUtil {
    private static MediaPlayer mMediaPlayer;
    private static AudioPlayProgressUtil mAudioPlayUtils;
    private ProgressListener mListener;
    private static Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            AudioPlayProgressUtil util = (AudioPlayProgressUtil) msg.obj;
            if (util != null && mMediaPlayer != null) {
                int currentPosition = mMediaPlayer.getCurrentPosition();
                util.setCurrentPosition(currentPosition);
                int progress = currentPosition * 100 / util.getDuration();
                if (util.getSeekBar() != null) {
                    if (progress != util.getSeekBar().getProgress())
                        util.getSeekBar().setProgress(progress);
                }
                if (util.getProgressListener() != null) {
                    util.getProgressListener().progress(progress, currentPosition, util.getDuration());
                }
                Message obtain = Message.obtain();
                obtain.what = 0;
                obtain.obj = util;
                sendMessageDelayed(obtain, 0);
            }
        }
    };
    private int mDuration;
    private int mCurrentPosition;
    private String url = "";
    private View mPlayView;
    private SeekBar mSeekBar;

    public AudioPlayProgressUtil() {
    }

    public AudioPlayProgressUtil(View playView) {
        this.mPlayView = playView;
    }

    public int getCurrentPosition() {
        return mCurrentPosition;
    }

    public void setCurrentPosition(int currentPosition) {
        this.mCurrentPosition = currentPosition;
    }

    public void setProgressListener(SeekBar seekBar, ProgressListener progressListener) {
        this.mSeekBar = seekBar;
        if (mSeekBar != null) {
            mSeekBar.setOnSeekBarChangeListener(new MyOnSeekBarChangeListener(this));
        }
        this.mListener = progressListener;
    }

    public void setProgressListener(ProgressListener progressListener) {
        this.mListener = progressListener;
    }

    public SeekBar getSeekBar() {
        return mSeekBar;
    }

    public int getDuration() {
        return mDuration;
    }

    public void setPlayView(View playView) {
        this.mPlayView = playView;
    }

    public View getPlayView() {
        return mPlayView;
    }

    public static class ProgressListener {
        public void start() {
        }

        public void progress(int progress, int currentDuration, int totalDuration) {
        }

        public void completion() {
        }

        public void stop() {
        }

        public void fail() {
        }
    }

    //开始播放录音
    public void play(String url) {
        if (TextUtils.isEmpty(url)) {
            ToastUtils.showShort("没有音频");
            return;
        }
        LogUtils.e("url:" + url);
        this.url = url;
        play(this);
    }

    public String getUrl() {
        return url;
    }

    public ProgressListener getProgressListener() {
        return mListener;
    }

    public void seekTo(int progress) {
        this.mCurrentPosition = progress * mDuration / 100;
        if (this == mAudioPlayUtils) {
            mMediaPlayer.seekTo(mCurrentPosition);
        }
    }

    private static void play(AudioPlayProgressUtil util) {
        if (util == mAudioPlayUtils) {
            return;
        }
        ProgressListener mListener = util.getProgressListener();
        try {
            if (mAudioPlayUtils != null) {
                mAudioPlayUtils.stop();
            }
            if (mMediaPlayer == null)
                mMediaPlayer = new MediaPlayer();
            mMediaPlayer.reset();
            mMediaPlayer.setDataSource(util.getUrl());
            mMediaPlayer.prepareAsync();
            mHandler.removeMessages(0);
            if (mListener != null) {
                mListener.start();
            }
            if (util.getPlayView() != null)
                util.getPlayView().setSelected(true);
            mMediaPlayer.setOnPreparedListener(mp -> {
                // 装载完毕回调
                if (util.getCurrentPosition() > 0)
                    mMediaPlayer.seekTo(util.getCurrentPosition());
                mMediaPlayer.start();
                int duration = mMediaPlayer.getDuration();
                LogUtils.e("duration:" + duration);
                util.setDuration(duration);
                Message msg = Message.obtain();
                msg.what = 0;
                msg.obj = util;
                mHandler.sendMessage(msg);
            });
            mMediaPlayer.setOnCompletionListener(mediaPlayer -> {
                if (mListener != null) {
                    mListener.stop();
                    mListener.completion();
                }
                if (util.getPlayView() != null)
                    util.getPlayView().setSelected(false);
                if (util.getSeekBar() != null) {
                    util.getSeekBar().setProgress(0);
                }
                util.setCurrentPosition(0);
                mHandler.removeMessages(0);
                mAudioPlayUtils = null;
            });
            mAudioPlayUtils = util;
        } catch (Exception e) {
            if (mListener != null) {
                mListener.stop();
                mListener.fail();
            }
            if (util.getPlayView() != null)
                util.getPlayView().setSelected(false);
            ToastUtils.showShort("播放音频失败");
            LogUtils.e("异常：" + e.toString());
            ToastUtil.showShort(e.getMessage());
            e.printStackTrace();
        }
    }

    private void setDuration(int duration) {
        this.mDuration = duration;
    }

    //结束录音播放
    public static void stop() {
        if (mMediaPlayer != null) {
            if (mAudioPlayUtils != null) {
                mAudioPlayUtils.setCurrentPosition(mMediaPlayer.getCurrentPosition());
                if (mAudioPlayUtils.mListener != null) {
                    mAudioPlayUtils.mListener.stop();
                }
                if (mAudioPlayUtils.getPlayView() != null)
                    mAudioPlayUtils.getPlayView().setSelected(false);
            }
            mMediaPlayer.stop();
//            mMediaPlayer.release();
//            mMediaPlayer = null;
        }
        if (mHandler != null) {
            mHandler.removeMessages(0);
        }
        mAudioPlayUtils = null;
    }


    class MyOnSeekBarChangeListener implements SeekBar.OnSeekBarChangeListener {
        private final AudioPlayProgressUtil playUtils;

        public MyOnSeekBarChangeListener(AudioPlayProgressUtil playUtils) {
            this.playUtils = playUtils;
        }

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            playUtils.seekTo(seekBar.getProgress());
        }
    }

    public static void getDurationByUrl(String url, DurationCallback callback) {
        try {
            MediaPlayer mediaPlayer = new MediaPlayer();
            mediaPlayer.reset();
            LogUtils.e("播放音频：" + url);
            mediaPlayer.setDataSource(url);
            mediaPlayer.prepareAsync();
            mediaPlayer.setOnPreparedListener(mp -> {
                // 装载完毕回调
                int duration = mediaPlayer.getDuration();
                LogUtils.e("duration:" + duration);
                if (callback != null)
                    callback.getDuration(duration);
            });
        } catch (Exception e) {
            LogUtils.e("获取市场异常：" + e.toString());
            e.printStackTrace();
        }
    }

    public interface DurationCallback {
        void getDuration(int duration);
    }

    private boolean mIsPlaying;

    public void autoPlay(String url) {
        if (mIsPlaying) {
            stop();
        } else {
            play(url);
        }
    }

    private void setPlaying(boolean isPlaying) {
        this.mIsPlaying = isPlaying;
        if (mPlayView != null)
            mPlayView.setSelected(isPlaying);
    }

}


//public class AudioPlayProgressUtil {
//    private static MediaPlayer mMediaPlayer;
//    private static AudioPlayProgressUtil mAudioPlayUtils;
//    private ProgressListener mListener;
//    private boolean mIsPlaying;
//
//    public AudioPlayProgressUtil() {
//    }
//
//    public AudioPlayProgressUtil(View playView) {
//        this.mPlayView = playView;
//    }
//
//    private static Handler mHandler = new Handler() {
//        @Override
//        public void handleMessage(Message msg) {
//            LogUtils.e("进来了" + System.currentTimeMillis());
//            AudioPlayProgressUtil util = (AudioPlayProgressUtil) msg.obj;
//            if (util != null && mMediaPlayer != null) {
//                int currentPosition = mMediaPlayer.getCurrentPosition();
//                LogUtils.e("currentPosition:" + currentPosition);
//                util.setCurrentPosition(currentPosition);
//                int progress = currentPosition * 100 / util.getDuration();
//                if (util.getProgressListener() != null) {
//                    util.getProgressListener().progress(progress, currentPosition, util.getDuration());
//                }
//                Message obtain = Message.obtain();
//                obtain.what = 0;
//                obtain.obj = util;
//                sendMessageDelayed(obtain, 1000);
//            }
//        }
//    };
//    private int mDuration;
//    private int mCurrentPosition;
//    private String url = "";
//    private View mPlayView;
//
//    public int getCurrentPosition() {
//        return mCurrentPosition;
//    }
//
//    public void setCurrentPosition(int currentPosition) {
//        this.mCurrentPosition = currentPosition;
//    }
//
//
//    public void setProgressListener(SeekBar seekBar, ProgressListener progressListener) {
//        this.mSeekBar = seekBar;
//        if (mSeekBar != null) {
//            mSeekBar.setOnSeekBarChangeListener(new MyOnSeekBarChangeListener(this));
//        }
//        this.mListener = progressListener;
//    }
//
//    public void setProgressListener(ProgressListener progressListener) {
//        this.mListener = progressListener;
//    }
//
//    public int getDuration() {
//        return mDuration;
//    }
//
//    public void setPlayView(View playView) {
//        this.mPlayView = playView;
//    }
//
//    public View getPlayView() {
//        return mPlayView;
//    }
//
//    public void autoPlay(String url) {
//        if (mIsPlaying) {
//            stop();
//        } else {
//            play(url);
//        }
//    }
//
//    public static class ProgressListener {
//        public void start() {
//        }
//
//        public void progress(int progress, int currentDuration, int totalDuration) {
//        }
//
//        public void completion() {
//        }
//
//        public void stop() {
//        }
//
//        public void fail() {
//        }
//    }
//
//    public interface DurationCallback {
//        public void getDuration(int duration);
//    }
//
//    //开始播放录音
//    public void play(String url) {
//        this.url = url;
//        play(this);
//    }
//
//    public String getUrl() {
//        return url;
//    }
//
//    public ProgressListener getProgressListener() {
//        return mListener;
//    }
//
//    public void seekTo(int progress) {
//        this.mCurrentPosition = progress * mDuration / 100;
//        if (this == mAudioPlayUtils) {
//            mMediaPlayer.seekTo(mCurrentPosition);
//        }
//    }
//
//    public static void getDurationByUrl(String url, DurationCallback callback) {
//        try {
//            MediaPlayer mediaPlayer = new MediaPlayer();
//            mediaPlayer.reset();
//            LogUtils.e("播放音频：" + url);
//            mediaPlayer.setDataSource(url);
//            mediaPlayer.prepareAsync();
//            mediaPlayer.setOnPreparedListener(mp -> {
//                // 装载完毕回调
//                int duration = mediaPlayer.getDuration();
//                LogUtils.e("duration:" + duration);
//                if (callback != null)
//                    callback.getDuration(duration);
//            });
//        } catch (Exception e) {
//            LogUtils.e("获取市场异常：" + e.toString());
//            e.printStackTrace();
//        }
//    }
//
//    private static void play(AudioPlayProgressUtil util) {
//        if (util == mAudioPlayUtils) {
//            return;
//        }
//        ProgressListener mListener = util.getProgressListener();
//        try {
//            if (mAudioPlayUtils != null) {
//                mAudioPlayUtils.stop();
//            }
//            if (mMediaPlayer == null)
//                mMediaPlayer = new MediaPlayer();
//            mMediaPlayer.reset();
//            LogUtils.e("播放音频：" + util.getUrl());
//            mMediaPlayer.setDataSource(util.getUrl());
//            mMediaPlayer.prepareAsync();
//            mHandler.removeMessages(0);
//            if (mListener != null) {
//                mListener.start();
//            }
//            util.setPlaying(true);
//            mMediaPlayer.setOnPreparedListener(mp -> {
//                // 装载完毕回调
//                if (util.getCurrentPosition() > 0)
//                    mMediaPlayer.seekTo(util.getCurrentPosition());
//                mMediaPlayer.start();
//                int duration = mMediaPlayer.getDuration();
//                LogUtils.e("duration:" + duration);
//                util.setDuration(duration);
//                Message msg = Message.obtain();
//                msg.what = 0;
//                msg.obj = util;
//                mHandler.sendMessage(msg);
//            });
//            mMediaPlayer.setOnCompletionListener(mediaPlayer -> {
//                if (mListener != null) {
//                    mListener.stop();
//                    mListener.completion();
//                }
//                util.setPlaying(false);
//                util.setCurrentPosition(0);
//                mHandler.removeMessages(0);
//                mAudioPlayUtils = null;
//            });
//            mAudioPlayUtils = util;
//        } catch (Exception e) {
//            if (mListener != null) {
//                mListener.stop();
//                mListener.fail();
//            }
//            util.setPlaying(false);
//            ToastUtils.showShort("播放音频失败");
//            LogUtils.e("异常：" + e.toString());
//            ToastUtil.showShort(e.getMessage());
//            e.printStackTrace();
//        }
//    }
//
//    private void setPlaying(boolean isPlaying) {
//        this.mIsPlaying = isPlaying;
//        if (mPlayView != null)
//            mPlayView.setSelected(isPlaying);
//    }
//
//    private void setDuration(int duration) {
//        this.mDuration = duration;
//    }
//
//    //结束录音播放
//    public static void stop() {
//        if (mMediaPlayer != null) {
//            if (mAudioPlayUtils != null) {
//                mAudioPlayUtils.setCurrentPosition(mMediaPlayer.getCurrentPosition());
//                if (mAudioPlayUtils.mListener != null) {
//                    mAudioPlayUtils.mListener.stop();
//                }
//                mAudioPlayUtils.setPlaying(false);
//            }
//            mMediaPlayer.stop();
////            mMediaPlayer.release();
////            mMediaPlayer = null;
//        }
//        if (mHandler != null) {
//            mHandler.removeMessages(0);
//        }
//        mAudioPlayUtils = null;
//    }
//}
